package com.starinside.wp.controller.api;

import com.google.common.collect.ImmutableMap;
import com.starinside.wp.config.WxMpProperties;
import com.starinside.wp.domain.Children;
import com.starinside.wp.domain.ChildrenHealthBaseInfo;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.domain.observation.ObservationListItemVO;
import com.starinside.wp.domain.observation.ObservationNewQuestionRecord;
import com.starinside.wp.foundation.dto.StaffDTO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.EvaluateQuery;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.repository.ChildrenObservationRecordRepository;
import com.starinside.wp.repository.ObservationNewQuestionRecordRepository;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.ChildrenHealthService;
import com.starinside.wp.service.ChildrenService;
import com.starinside.wp.utils.RemoteCallUtil;
import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Record;
import com.tuo51.evaluate.service.EvaluateV2ConclusionService;
import com.tuo51.evaluate.service.EvaluateV2Service;
import com.tuo51.evaluate.vo.evaluate.WebEvaluateRecordListVo;
import com.tuo51.foudation.utils.CopyUtils;
import com.tuo51.foudation.utils.export.HealthReportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@EnableConfigurationProperties(WxMpProperties.class)
@RestController
@RequestMapping("/wx/api/reports")
@Api(value = "/wx/api/reports", tags = "观测点/儿保/评测 报告")
public class APIReportsController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private WxMpService wxService;

    @Autowired
    private ChildrenObservationRecordRepository childrenObservationRecordRepository;

    @Autowired
    private ObservationNewQuestionRecordRepository observationNewQuestionRecordRepository;

    @Autowired
    public APIReportsController(WxMpService wxService) {
        this.wxService = wxService;
    }

    @Autowired
    private ChildrenHealthService childrenHealthService;

    @Autowired
    BindedBabyService bindedBabyService;
    @Autowired
    private ChildrenService childrenService;

    @RequestMapping(value = "/children_health/page", method = RequestMethod.GET)
    @ApiOperation(value = "查询当前小朋友的儿保评测列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse page(HttpServletRequest req, HttpServletResponse resp, PagerQuery pagerQuery) {

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        Page<ChildrenHealthBaseInfo> childrenPage = childrenHealthService.getChildChildrenHealthPage(loginUser.getDefaultBabyId(), pagerQuery);
        childrenPage.forEach(e -> {
            String name = childrenService.getById(e.getChildrenId()).getName();
            if (name != null && !name.isEmpty()) {
                e.setChildrenName(name);
            }
        });
        return StatusResponse.success(childrenPage);
    }

    @RequestMapping(value = "/children_health/detail", method = RequestMethod.GET)
    @ApiOperation(value = "查询当前小朋友的儿保评测详情")
    @ApiImplicitParam(name = "id", value = "儿保评测 id")
    public StatusResponse page(String id) {
        Map healthMap = childrenHealthService.findHealthInfoDetail(id);
        return StatusResponse.success(healthMap);
    }


    @RequestMapping(value = "/observation/list", method = RequestMethod.GET)
    @ApiOperation("课堂观测点列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "childrenId", value = "宝贝 id， 如果不特别指定，择返回当前用户所有宝宝的数据"),
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse observationList(HttpServletRequest req, HttpServletResponse resp,
                                          String childrenId, PagerQuery pagerQuery) {

        //先取此用户基本信息
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        //取此用户下所有孩子的id
        String[] childrenIds = null;
        if(StringUtils.isEmpty(childrenId)) {
            List<BindedBabyVO> babies = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());
            childrenIds = babies.stream().map(k -> {
                return k.getId();
            }).toArray(String[]::new);
        }else{
            childrenIds = new String[]{childrenId};
        }

        Page observations = childrenObservationRecordRepository.findAllByChildrenIds(childrenIds, pagerQuery);

        return StatusResponse.success(observations);
    }

    @RequestMapping(value = "/observation/detail", method = RequestMethod.GET)
    @ApiOperation("课堂观测点详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "观测点 id"),
    })
    public StatusResponse observationDetail(String id) {
        ObservationListItemVO object = childrenObservationRecordRepository.findByRecordId(id);

        List<ObservationNewQuestionRecord> questions = observationNewQuestionRecordRepository.findAllQuestionGroupedByTitle(id);

        object.setQuestions(questions);

        return StatusResponse.success(object);
    }


    @Autowired
    private EvaluateV2Service evaluateService;

    @Autowired
    private EvaluateV2ConclusionService conclusionService;

    @RequestMapping(value = "/bmi/info", method = GET)
    public StatusResponse bmiInfo(@RequestHeader(TICKET) String ticket,
                                  @RequestParam(name = "name", required = false) String name,
                                  @RequestParam(name = "gender", required = true) Integer gender,
                                  @RequestParam(name = "birthday", required = false) String birthday,
                                  @RequestParam(name = "weight", required = false) String weight,
                                  @RequestParam(name = "height", required = false) String height
    ){
        return StatusResponse.success(HealthReportUtil.bmiInfo(name, gender, birthday, weight, height));
    }

    @RequestMapping(value = "/pb/list", method = RequestMethod.GET)
    @ApiOperation("儿心量表测评报告列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "childrenId", value = "宝贝 id， 如果不特别指定，择返回当前用户所有宝宝的数据"),
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    public StatusResponse pbList(HttpServletRequest req, HttpServletResponse resp,
                                 @RequestHeader(TICKET) String ticket,
                                 String childrenId, PagerQuery pagerQuery) {

        //先取此用户基本信息
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        //取此用户下所有孩子的id
        String[] childrenIds = null;
        if(StringUtils.isEmpty(childrenId)) {
            List<BindedBabyVO> babies = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());
            childrenIds = babies.stream().map(k -> {
                return k.getId();
            }).toArray(String[]::new);
        }else{
            childrenIds = new String[]{childrenId};
        }

        Page<WebEvaluateRecordListVo> recordPage = evaluateService.getEvaluatePage(childrenIds, pagerQuery);

        return StatusResponse.success(recordPage);
    }

    @RequestMapping(value = "/pb/detail", method = RequestMethod.GET)
    @ApiOperation("儿心量表测评报告详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "报告 id"),
    })
    public StatusResponse pbDetail(HttpServletRequest req, HttpServletResponse resp,
                                   @RequestHeader(TICKET) String ticket,
                                   String reportId) {

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        EvaluateV2Record object = evaluateService.getEvaluateDetail(reportId);

        List<BindedBabyVO> babies = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());
        boolean found = false;
        for (BindedBabyVO b : babies){
            if (object.getChildrenId().equals(b.getId())){
                found = true;
                break;
            }
        }

        if (!found){
            throw new BusinessException(ErrorCode.EVALUATE_RECORD_NOT_EXIST, "报告不存在");
        }
        Map result = conclusionService.generateReportExtInfo(object);

        Map objMap = CopyUtils.transBean2Map(object);
        result.putAll(objMap);

        return StatusResponse.success(result);
    }


}
